import React, { useState } from 'react';
import { Button, message } from 'antd';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormCascader,
  ProFormSelect,
  ProFormSwitch,
  ProFormTextArea,
  ProFormDependency,
  ProFormUploadDragger,
} from '@ant-design/pro-form';
import { CloseOutlined, CheckOutlined } from '@ant-design/icons';
import reqwest from 'reqwest';

import { pinyin } from 'pinyin-pro';

import request from 'umi-request';

import { api } from '@/global';

const randomSalt = (n = 1): number => {
  const max = Math.pow(10, n) - 1;
  const min = Math.pow(10, n - 1);
  return Math.round(Math.random() * (max - min)) + min;
};

type folderType = {
  bucketName: string;
  children: string;
  id: number;
  parent: number;
  pathCode: string;
  pathName: string;
  childrenList: folderType[];
};

type resultType = {
  fileDesc: string;
  fileName: string;
  fileown: string;
  filepathId: any[];
  isAutoName: boolean;
  fileDescribe: string;
  isCurrentUserInfo: boolean;
  file: any[];
};

const generateNode: any = (item: folderType) => {
  if (!item) {
    return;
  }

  const result = {
    value: item.id,
    label: item.pathName,
  };
  if (item.childrenList) {
    result['children'] = item.childrenList.map((i) => {
      return generateNode(i);
    });
  }

  return result;
};

export default (props: any) => {
  const [fileInfo, SetFileInfo] = useState();

  return (
    <ModalForm<{
      name: string;
      company: string;
    }>
      title="上传"
      trigger={<a>上传文件</a>}
      autoFocusFirstInput
      modalProps={{
        onCancel: () => console.log('run'),
      }}
      onFinish={async (r: resultType) => {
        // 判断是否有文件了
        if (!fileInfo) {
          message.error('请选择文件');
          return;
        }

        // 解析数据
        let filePathId = 0;
        if (typeof r.filepathId[r.filepathId.length - 1] == 'number') {
          filePathId = r.filepathId[r.filepathId.length - 1];
        }
        const bucketInfo = await request(api.getBucketInfo);
        const tempId = bucketInfo.data.filter((item) => item.bucketName === r.filepathId[0]);
        const fileBucketId = tempId[0].id;
        const fileOwnerId = r.fileown;
        const fileDescribe = r.fileDescribe;
        const isAutoName = r.isAutoName == undefined ? false : r.isAutoName;
        const isCurrentUserInfo = r.isCurrentUserInfo == undefined ? true : r.isCurrentUserInfo;
        let fileName;
        if (isAutoName) {
          fileName = r.fileName;
        } else {
          fileName = r.file[0].name;
        }

        const formData = new FormData();
        formData.append('filePathId', filePathId + '');
        formData.append('fileBucketId', fileBucketId);
        formData.append('fileOwnerId', fileOwnerId);
        formData.append('fileDescribe', fileDescribe);
        formData.append('fileName', fileName);
        formData.append('isCurrentUserInfo', isCurrentUserInfo + '');

        formData.append('file', fileInfo);

        const result = await request(api.uploadFile, {
          method: 'post',

          data: formData,
        });

        if (result.success) {
          message.info('保存成功');
          props?.getAllFileInfo();
        } else {
          message.error('保存失败');
        }
        return true;
      }}
    >
      <ProForm.Group>
        <ProFormSwitch
          width="sm"
          name="isAutoName"
          tooltip="是否使用文件原名称"
          label="选中后可以自定义名称"
          validateFirst={false}
          fieldProps={{
            checkedChildren: <CheckOutlined />,
            unCheckedChildren: <CloseOutlined />,
            defaultChecked: false,
          }}
        />
        <ProFormDependency name={['isAutoName']}>
          {({ isAutoName }) => {
            return (
              <ProFormText
                width="md"
                name="fileName"
                label="文件名称"
                disabled={isAutoName === undefined ? true : !isAutoName}
                placeholder="请输入文件名称"
              />
            );
          }}
        </ProFormDependency>
      </ProForm.Group>

      <ProForm.Group>
        <ProFormCascader
          name="filepathId"
          width="xl"
          label="需要创建的父级文件夹"
          fieldProps={{
            changeOnSelect: true,
          }}
          rules={[
            {
              required: true,
              message: '请选择文件夹',
            },
          ]}
          request={async () => {
            const result = await request(api.getFolderList);

            const data: folderType = result.data;
            const alist: any[] = [];

            Object.keys(data).map((item, index) => {
              alist.push({
                value: item,
                label: item,
                children: data[item].map((c: folderType) => {
                  return generateNode(c);
                }),
              });
            });

            return alist;
          }}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSwitch
          width="sm"
          name="isCurrentUserInfo"
          tooltip="是否为当前用户"
          label="是否为当前用户"
          fieldProps={{
            checkedChildren: <CheckOutlined />,
            unCheckedChildren: <CloseOutlined />,
            defaultChecked: true,
          }}
        />
        <ProFormDependency name={['isCurrentUserInfo']}>
          {({ isCurrentUserInfo }) => {
            return (
              <ProFormSelect
                name="fileown"
                disabled={isCurrentUserInfo === undefined ? true : isCurrentUserInfo}
                label="文件负责人"
                request={async () => {
                  const list: any[] = [];
                  const result = await request(api.getSimpleUserInfo);

                  result.data.forEach((item) => {
                    list.push({ label: item.name, value: item.id });
                  });

                  return list;
                }}
                placeholder="请选择文件负责人"
              />
            );
          }}
        </ProFormDependency>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormTextArea width="lg" name="fileDescribe" label="文件描述" placeholder="文件描述" rules={[
          {
            required: true,
            message: '请输入文件描述',
          },
        ]} />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormUploadDragger
          max={1}
          width="xl"
          label="选择文件"
          name="file"
          description="仅支持单次上传"
          fieldProps={{
            beforeUpload: (file) => {
              SetFileInfo(file);
              return false;
            },
          }}
          rules={[
            {
              required: true,
              message: '请选择文件夹',
            },
          ]}
        />
      </ProForm.Group>
    </ModalForm>
  );
};
